(function(global) {

    const serverUrl = 'http://127.0.0.1:2080'
    const serverApiUrl = 'http://127.0.0.1:2080/api'


    // 
    const unitConvert = function(num) {
        var moneyUnits = ["", "万", "亿", "万亿"]
        var dividend = 10000
        var curentNum = parseInt(num) //转换数字 
        var curentUnit = moneyUnits[0] //转换单位 
        for (var i = 0; i < 4; i++) {
            curentUnit = moneyUnits[i]
            if (strNumSize(curentNum) < 5) {
                break;
            }
            curentNum = curentNum / dividend
        }
        var m = {
                num: 0,
                unit: ""
            }
            //m.num = curentNum.toFixed(2)
            //m.unit = curentUnit
        return curentNum.toFixed(2) + curentUnit
    }

    const strNumSize = function(tempNum) {
        var stringNum = tempNum.toString()
        var index = stringNum.indexOf(".")
        var newNum = stringNum
        if (index != -1) {
            newNum = stringNum.substring(0, index)
        }
        return newNum.length
    }

    // 
    const getArtistNames = function(artists) {
        let names = "";
        for (i in artists) {
            if (i == 0) {
                names = names + artists[i].name;
            } else {
                names = names + " / " + artists[i].name;
            }
        }
        return names;
    }

    // 加载模板
    var loadTemplate = function(name) {
        id = name + "_tmpl";
        return document.getElementById(id).innerHTML;
    }

    //
    const pad = (num, n) => (Array(n).join(0) + num).slice(-n)

    const convertDuration = duration => {
        const h = Math.floor(duration / 3600)
        const m = Math.floor(duration % 3600 / 60)
        const s = Math.floor(duration % 60)
        return h ? `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)}` : `${pad(m, 2)}:${pad(s, 2)}`
    }


    // 当天
    const getToday = function() {
        //获取当前时间
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        if (month < 10) {
            month = "0" + month;
        }
        if (day < 10) {
            day = "0" + day;
        }
        var nowDate = year + "年" + month + "月" + day + "日";
        return nowDate
    }

    // 停止海报
    const stopPoster = function() {
        var els = document.getElementsByClassName('a-circling');
        for (i = 0; i < els.length; i++) {
            els[i].classList.add("z-pause");
        }
    }
    const startPoster = function() {
        var els = document.getElementsByClassName('a-circling');
        for (i = 0; i < els.length; i++) {
            els[i].classList.remove("z-pause");
        }
    }



    /////////////////////////////////


    // 首页
    var Home = {
        template: loadTemplate('home'),
        data: function() {
            return {
                serverUrl: serverUrl,
                // 推荐歌单
                remd_high: 1000000,
                // 推荐歌单
                recommends: [],
                // 最新音乐
                lastest_songs: []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            unitConvert: unitConvert,
            getArtistNames: getArtistNames,
            fetchData() {
                this.error = this.recommends = this.lastest_songs = null
                this.loading = true
                    // 获取推荐歌单
                this.getRecommends();
                // 获取最近歌曲
                this.getSongsLatest();
            },
            getSongsLatest() {
                this.$http.jsonp(`${serverApiUrl}/music/latest`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        this.loading = false
                        this.error = null
                        this.lastest_songs = res.data
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            getRecommends() {
                this.$http.jsonp(`${serverApiUrl}/songs/latest`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        //console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.recommends = res.data
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            },
        }
    }

    // 热歌
    var Hot = {
        template: loadTemplate('hot'),
        data: function() {
            return {
                "tracks": []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            getToday: getToday,
            getArtistNames: getArtistNames,
            fetchData() {
                this.error = this.recommends = this.lastest_songs = null
                this.loading = true

                // 获取推荐歌单
                this.getHots();
            },
            getHots() {
                this.$http.jsonp(`${serverApiUrl}/music/hot`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        //console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.tracks = res.data
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
        }
    }



    // 歌单列表
    var Songs = {
        template: loadTemplate('songs'),
        data: function() {
            return {
                serverUrl: serverUrl,
                showMore: false,
                songs: {},
                list: [],
                user: {},
                song_desc: null,
                tags: []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            unitConvert: unitConvert,
            fetchData() {
                this.error = this.player = null
                this.loading = true

                this.getSongs(this.$route.params.id);
                this.getTags()
            },
            getSongs(id) {
                this.$http.jsonp(`${serverApiUrl}/songs/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        this.loading = false
                        this.error = false
                        this.songs = res.data.songs
                        this.list = res.data.list
                        this.user = res.data.user
                        this.song_desc = this.songs.desc

                        // console.log(this.songs)
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            },
            getTags() {
                this.$http.jsonp(`${serverApiUrl}/tag`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        this.loading = false
                        this.error = false
                        this.tags = res.data

                        // console.log(this.tags)
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            },
            showDesc() {
                this.showMore = !this.showMore
            }
        }
    }

    // 全局变量，避免重复初始
    const audio = new Audio()
        // 播放器
    var Player = {
        template: loadTemplate('player'),
        data: function() {
            return {
                serverUrl: serverUrl,
                poster_transform: null,
                loading: false,
                error: {},
                player: {
                    album: {},
                    artist: {}
                },
                showOther: false,
                showSong: true,
                scroll: {},
                fullHeight: 0,
                fullHeightStyle: null
            }
        },
        created() {
            this.initPlayer()
            this.handleResize()
        },
        mounted() {
            this.initScroll()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'initPlayer'
        },
        ready: function() {
            window.addEventListener('resize', this.handleResize)
        },
        beforeDestroy: function() {
            window.removeEventListener('resize', this.handleResize)
        },
        methods: {
            convert: convertDuration,
            // 初始化播放器配置
            initPlayer() {
                this.loading = true
                let id = this.$route.params.id

                this.$http.jsonp(`${serverApiUrl}/music/${id}`).then(res => {

                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        let player = { current: 0, playing: false, random: false }
                        Object.assign(player, res.data)

                        this.loading = false
                        this.error = {}
                        this.player = player

                        this.initAudio()

                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            },
            // 初始化播放器
            initAudio() {
                audio.src = serverUrl + this.player.music
                audio.autoplay = false
                audio.addEventListener('loadedmetadata', () => {
                    this.player.duration = audio.duration
                })
                audio.addEventListener('timeupdate', () => {
                    this.player.current = audio.currentTime
                })
                audio.addEventListener('play', () => {
                    this.player.playing = true
                })
                audio.addEventListener('pause', () => {
                    this.player.playing = false
                })

            },
            play() {
                if (this.player.playing) {
                    this.stopPoster()
                    audio.pause()
                } else {
                    this.startPoster()
                    audio.play()
                }
                this.player.playing = !this.player.playing
            },
            progress() {
                audio.currentTime = this.player.current
            },
            next() {
                this.$http.jsonp(`${serverApiUrl}/music`).then(res => {
                    const ids = res.data.map(s => s.id)
                    let targetIndex = ids.indexOf(this.player.id) + 1
                    if (targetIndex >= ids.length) {
                        targetIndex = 0
                    }
                    router.go({ name: 'player', params: { id: ids[targetIndex] } })
                })
            },
            prev() {
                this.$http.jsonp(`${serverApiUrl}/music`).then(res => {
                    const ids = res.data.map(s => s.id)
                    let targetIndex = ids.indexOf(this.player.id) - 1
                    if (targetIndex < 0) {
                        targetIndex = ids.length - 1
                    }
                    router.go({ name: 'player', params: { id: ids[targetIndex] } })
                })
            },
            // 停止海报
            stopPoster() {
                var el = document.getElementById("poster_img");
                var st = window.getComputedStyle(el, null);
                var tr = st.getPropertyValue("-webkit-transform") ||
                    st.getPropertyValue("-moz-transform") ||
                    st.getPropertyValue("-ms-transform") ||
                    st.getPropertyValue("-o-transform") ||
                    st.getPropertyValue("transform") ||
                    "FAIL";

                // console.log(tr)
                this.poster_transform = tr

            },
            startPoster() {
                // this.poster_transform 
            },
            handleResize() {
                this.fullHeight = document.documentElement.clientHeight - 60
                this.fullHeightStyle = this.fullHeight + 'px'
            },
            initScroll() {  
                this.scroll = new BScroll(this.$refs.wrapper, {
                    click: true,
                    scrollY: true,
                    fade: true
                })

                // 绑定事件
                this.scroll.on('scroll', function(position) {
                    if (position.y > 30) {
                        //console.log('释放立即刷新')
                    }
                });


                let scroll = this.scroll

                // 滑动结束
                this.scroll.on('touchEnd', function(position) {

                    if (position.y > 30) {
                        setTimeout(function() {
                            /**
                             * 这里发送ajax刷新数据
                             * 刷新后,后台只返回第1页的数据,无论用户是否已经上拉加载了更多
                             */
                            // 恢复文本值
                            //console.log('下拉刷新')
                            // 刷新成功后的提示
                            //console.log('刷新成功')

                            // 刷新列表后,重新计算滚动区域高度
                            scroll.refresh();

                        }, 1000);
                    } else {
                        //console.log('刷新成功')
                        setTimeout(function() {
                            // 恢复文本值 
                            //console.log('查看更多')
                            // 向列表添加数据
                            // 加载更多后,重新计算滚动区域高度
                            scroll.refresh();

                        }, 1000);
                    }
                }); 
            },
            scrollOther() {
                if (this.scroll) {
                    this.scroll.scrollTo(0, 0 - this.fullHeight);
                }
            }
        }
    }

    // 搜索
    var Search = {
        template: loadTemplate('search'),
        data: function() {
            return {
                serverUrl: serverUrl,
                hot_words: [],
                holder: '搜索歌曲',
                showClear: false,
                keyword: '',
                showDefault: true,
                showSearch: false,
                showMatch: false,

                matches: [],
                histories: [],

                artist: {},
                album: {
                    artist: {}
                },
                list: []

            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            fetchData() {
                this.error = this.hot_words = null
                this.loading = true

                // 获取推荐歌单
                this.getHots();
                // 获取搜索历史
                this.getHistories(1);

            },
            getHots() {
                this.$http.jsonp(`${serverApiUrl}/search/hot`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        this.loading = false
                        this.error = null
                        this.hot_words = res.data
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            getMatches(keyword) {
                this.$http.jsonp(`${serverApiUrl}/search/match/${keyword}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        //console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.matches = res.data

                        //console.log(res.data)
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            getHistories(uid) {
                //console.log(uid)
                this.$http.jsonp(`${serverApiUrl}/search/history/${uid}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        //console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.histories = res.data
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            clear() {
                this.holder = '搜索歌曲';
                this.showClear = false;
                this.showDefault = true;
                this.showMatch = false;
                this.showSearch = false;
                this.keyword = ''
            },
            clean() {
                this.holder = ''
                    //this.keyword = ''
            },
            show(ev) {
                this.showClear = true;

                // 回车查询
                if (ev.keyCode == 13) {
                    this.showDefault = false;
                    this.showSearch = true;
                    this.showMatch = false;
                    this.doSearch(this.keyword)
                } else {
                    this.showMatch = true
                    this.showDefault = false
                    this.showSearch = false
                    this.getMatches(this.keyword)
                }

            },
            doSearch(keyword) {
                this.$http.jsonp(`${serverApiUrl}/search/${keyword}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        //console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.artist = res.data.artist
                        this.list = res.data.list
                        this.album = res.data.album
                    }
                    //console.log(this.searchContent)
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            removeSearch(index) {
                this.histories.splice(index, 1)
            }
        }
    }



    // 用户
    var User = {
        template: loadTemplate('user'),
        data: function() {
            return {
                serverUrl: serverUrl,
                songs_total: 0,
                collection: {},
                user: {},
                list: []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            unitConvert: unitConvert,
            fetchData() {
                this.error = this.player = null
                this.loading = true

                this.getUser(this.$route.params.id);
                this.getSongs(this.$route.params.id);
                this.getCollection(this.$route.params.id);

            },
            getUser(id) {
                this.$http.jsonp(`${serverApiUrl}/user/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {

                        this.loading = false
                        this.error = null
                        this.user = res.data
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            getSongs(id) {
                this.$http.jsonp(`${serverApiUrl}/user/songs/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {

                        this.loading = false
                        this.error = null
                        this.list = res.data
                        this.songs_total = this.list.length
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            },
            getCollection(id) {
                this.$http.jsonp(`${serverApiUrl}/user/collection/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {

                        this.loading = false
                        this.error = null
                        this.collection = res.data
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            }
        }
    }

    // 歌手
    var Artist = {
        template: loadTemplate('artist'),
        data: function() {
            return {
                hot_song_num: 20,
                showDesc: false,
                artist: {},
                list: [],
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            showMore() {
                this.showDesc = !this.showDesc;
            },
            fetchData() {
                this.error = this.player = null
                this.loading = true

                this.getArtist(this.$route.params.id);

            },
            getArtist(id) {
                this.$http.jsonp(`${serverApiUrl}/artist/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {

                        this.loading = false
                        this.error = null
                        this.list = res.data.musics
                        this.artist = res.data.artist
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            }
        }
    }

    // 专辑
    var Album = {
        template: loadTemplate('album'),
        data: function() {
            return {
                serverUrl: serverUrl,
                artist: {},
                album: {},
                list: []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            fetchData() {
                this.error = null
                this.loading = true

                this.getAlbum(this.$route.params.id);

            },
            getAlbum(id) {
                this.$http.jsonp(`${serverApiUrl}/album/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        // console.log(res.data)
                        this.loading = false
                        this.error = null
                        this.list = res.data.list
                        this.artist = res.data.artist
                        this.album = res.data.album
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            }
        }
    }

    // 所有歌单
    var SongsList = {
        template: loadTemplate('songs_list'),
        data: function() {
            return {
                serverUrl: serverUrl,
                remd_high: 10000,
                songs_list: []
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            unitConvert: unitConvert,
            fetchData() {
                this.error = null
                this.loading = true
                this.getSongs();
            },
            getSongs() {
                this.$http.jsonp(`${serverApiUrl}/songs`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        // console.log(res.data)
                        this.loading = false
                        this.error = null
                        for (i = 0; i < res.data.length; i++) {
                            this.songs_list.push(res.data[i])
                        }
                        // console.log(this.songs_list)
                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })
            }
        }

    }

    // 播放列表
    var Playlist = {
        template: loadTemplate('playlist'),
        data: function() {
            return {
                songs: [],
                ap: null
            }
        },
        created: function() {
            //this.initPlayer()
        },
        mounted: function() {
            this.initPlayer()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'initPlayer'
        },
        methods: {
            initPlayer() {
                this.$http.jsonp(`${serverApiUrl}/music`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'
                    } else {
                        // console.log(res.data)
                        this.loading = false
                        this.error = null

                        // 播放列表音乐
                        let songs = res.data
                        this.songs = songs

                        //console.log(songs)

                        // 处理音乐
                        let audios = []
                        for (i in songs) {
                            audios.push({
                                name: songs[i].name,
                                artist: songs[i].artist.name,
                                url: serverUrl + songs[i].music,
                                cover: serverUrl + songs[i].poster,
                                lrc: serverUrl + songs[i].lyric,
                            })
                        }

                        if (!this.ap) {
                            const ap = new APlayer({
                                container: document.getElementById('aplayer'),
                                mini: false,
                                autoplay: false,
                                theme: '#FADFA3',
                                loop: 'all',
                                lrcType: 3,
                                listMaxHeight: 100,
                                //fixed: true,
                                audio: audios
                            })

                            // 根据封面设置背景
                            const colorThief = new ColorThief();
                            const setTheme = (index) => {
                                if (!ap.list.audios[index].theme) {
                                    colorThief.getColorAsync(ap.list.audios[index].cover, function(color) {
                                        ap.theme(`rgb(${color[0]}, ${color[1]}, ${color[2]})`, index);
                                    });
                                }
                            };
                            setTheme(ap.list.index);
                            ap.on('listswitch', (index) => {
                                setTheme(index);
                            });

                            this.ap = ap

                        }

                    }
                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            }
        }
    }

    /**
     * 路由
     */
    var routes = [{
            path: '/',
            redirect: '/home'
        },
        {
            name: 'home',
            path: '/home',
            component: Home,
        },
        {
            name: 'hot',
            path: '/hot',
            component: Hot,
        },
        {
            name: 'search',
            path: '/search',
            component: Search,
        },
        {
            name: 'songs_list',
            path: '/songs_list',
            component: SongsList,
        },
        {
            name: 'songs',
            path: '/songs/:id',
            component: Songs,
        },
        {
            name: 'player',
            path: '/player/:id',
            component: Player,
        },
        {
            name: 'user',
            path: '/user/:id',
            component: User,
        },
        {
            name: 'artist',
            path: '/artist/:id',
            component: Artist,
        },
        {
            name: 'album',
            path: '/album/:id',
            component: Album,
        },
        {
            name: 'playlist',
            path: '/playlist',
            component: Playlist,
        },
    ]

    var router = new global.VueRouter({
        routes,
        scrollBehavior(to, from, savedPosition) {
            // return 期望滚动到哪个的位置
            if (to.hash) {
                return {
                    selector: to.hash
                }
            }
            if (savedPosition) {
                return savedPosition
            } else {
                return { x: 0, y: 0 }
            }
        }
    })

    const app = new global.Vue({
        router
    }).$mount('#j-app')



})(this)